package com.baic.ibase.service.users.impl;

import com.baic.ibase.controller.BusinessException;
import com.baic.ibase.mapper.UsersMapper;
import com.baic.ibase.models.dao.Users;
import com.baic.ibase.models.req.AuthLoginReq;
import com.baic.ibase.models.req.common.ApiResponse;
import com.baic.ibase.models.vo.AuthLoginResp;
import com.baic.ibase.service.users.AuthService;
import com.baic.ibase.utils.token.TokenUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;


@Slf4j
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private UsersMapper usersMapper;

    @Override
    public ApiResponse<AuthLoginResp> login(AuthLoginReq req) {
        ApiResponse<AuthLoginResp> resp = ApiResponse.ok();
        AuthLoginResp authLoginResp = new AuthLoginResp();

        LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(req.getUsername() != null, Users::getUsername, req.getUsername());

        Users user = usersMapper.selectOne(queryWrapper);
        if (user ==  null || user.getStatus() != 1 || !DigestUtils.md5DigestAsHex(req.getPassword().getBytes()).equals(user.getPassword())) {
            return ApiResponse.error(401, "用户名密码错误!", "用户名密码错误");
        }

        authLoginResp.setUserId(user.getId().toString());
        authLoginResp.setUserName(user.getUsername());
        authLoginResp.setToken(TokenUtils.createToken(user.getId().toString(), user.getUsername()));
        resp.setData(authLoginResp);

        return resp;
    }

    @Override
    public ApiResponse<Boolean> logout() {
        return null;
    }
}
